﻿using EentitfFrameworkMvc.common;
using EentitfFrameworkMvc.Models;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;


namespace EentitfFrameworkMvc.Controllers
{
    [EnableCors]  //对该控制器类开启跨域请求，在Program.cs中配置跨域信息
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class HomeController : Controller
    {
        //实例化数据库上下文类
        private readonly Data01Context _context;
        //向控制器类注入数据库字符串
        public HomeController(Data01Context context)
        {
            _context = context;
        }

        /*public HomeController(ILogger<HomeController> context)
        {
            _context = new Data01Context(new DbContextOptions<Data01Context>());
            //判断，如果当前数据库的数量为0，那么增加一条数据如下所示
            if (_context.TbStudent.Count() == 0)
            {
                _context.TbStudent.Add(new TbStudent { Sname = "admin", Spwd = "123456", Ssex = "女", Sage = 11, Ssf = "15555413354" });
                _context.SaveChanges();
            }
        }*/

        /// <summary>
        /// 根据姓名进行模糊查询，keyword
        /// </summary>
        /// <param name="KeyWord"></param>
        /// <returns></returns>
        [HttpGet]
        // GET: api/Home/SelectByKeyWord
        public OutPutResult<TbStudent> SelectByKeyWord(string name, int pageNumber, int pageSize)
        {
            //Data01Context context = new Data01Context();
            // 查询所有的数据.返回数组集合
                var data = _context.TbStudent.ToList();
            //如果KeyWord不为空的话，根据条件进行模糊查询
           // if (!string.IsNullOrEmpty(name))
            //{
                var skipCount = (pageNumber) * pageSize;
                data = _context.TbStudent.Where(s => s.Sname!.Contains(name)).OrderBy(s => s.Sid).Skip(skipCount).Take(pageSize).ToList();
                //data = _context.TbStudent.OrderBy(s => s.Sid).Skip(skipCount).Take(pageSize).ToList();
                int count = _context.TbStudent.Where(s => s.Sname!.Contains(name)).Count();
            return new OutPutResult<TbStudent> {Data = data , TotalRows = count };
            //}

        }

        /// <summary>
        /// 根据输入的参数进行分页查询，pageNumber:页码从0开始  pageSize：每页显示的记录数
        /// </summary>
        /// <param name="pageNumber"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public OutPutResult<TbStudent> SelectPageSize(int pageNumber, int pageSize)
        {
            var skipCount = (pageNumber) * pageSize;
            var data = _context.TbStudent.OrderBy(s => s.Sid).Skip(skipCount).Take(pageSize).ToList();
            int count = _context.TbStudent.Count();
            return new OutPutResult<TbStudent> {Data = data , TotalRows = count };
        }


        /// <summary>
        /// 登录验证，当用户输入账号和密码的时候，会请求接口进行校验，匹配成功则返回true，否则返回false
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpGet]
        public bool Login(int id, string pwd)
        {
            //查找Sid=id && Spwd=pwd的第一条数据
            var data = _context.TbStudent.Where(x => x.Sid == id && x.Spwd.Equals(pwd)).FirstOrDefault();
            if(data != null)
            {
                return true;
            }
            return false;
        }



        /// <summary>
        /// 查询全部，
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        // GET: api/Home/SelectAll
        //返回TbStudent实体类数组集合
        public List<TbStudent> SelectAll()
        {
            var data = _context.TbStudent.ToList();
            int count = _context.TbStudent.Count();
            return data;
        }

        /// <summary>
        /// 修改操作，先根据Id查询出来数据，再根据该数据的id进行数据的修改
        /// </summary>
        /// <param name="student"></param>
        [HttpPost]
        // Post: api/Home/UpdateById
        public bool UpdateById([FromBody] TbStudent student)
        {
            var data = _context.TbStudent.Where(x => x.Sid == student.Sid).FirstOrDefault();
            //把我们新的值，赋值到老的这条数据上
            data.Sname = student.Sname;
            data.Spwd = student.Spwd;
            data.Ssex = student.Ssex;
            data.Sage = student.Sage;
            data.Ssf = student.Ssf;
            //最后做一个保存数据的操作
            int count = _context.SaveChanges();
            if(count == 1)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 删除操作，根据id查询该数据是否存在，若存在则返回该数据的id进行删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        // Post: api/Home/DeleteById
        public bool DeleteById([FromBody] int id)
        {
            var data = _context.TbStudent.Where(x => x.Sid == id).FirstOrDefault();
            //所查询的数据不为空时执行删除操作
            if (data != null)
            {
                _context.TbStudent.Remove(data);
                _context.SaveChanges();
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 批量删除操作，前端传一个数组id，遍历数组进行删除操作
        /// </summary>
        /// <param name="entityIds"></param>
        [HttpPost]
        public void DeleteByIds([FromBody] int[] entityIds)
        {
            foreach (var id in entityIds)
            {
                var data = _context.TbStudent.Where(x => x.Sid == id).FirstOrDefault();
                if (data != null)
                {
                    _context.TbStudent.Remove(data);
                    _context.SaveChanges();
                }
            }
        }

        /// <summary>
        /// 数据新增，由于该对象的id是自增的，因此从前端返回除了id之外的Json数据即可
        /// </summary>
        /// <param name="student"></param>
        /// <returns></returns>
        [HttpPost]
        // Post: api/Home/SaveAdd
        public bool SaveAdd([FromBody] TbStudent student)
        {
            _context.Add(student);
            var count = _context.SaveChanges();
            if (count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}
